package com.bawei.module_home.ui.sign

import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.lib_common.Router
import com.bawei.lib_common.base.BaseActivity
import com.bawei.lib_common.base.BaseViewModel
import com.bawei.lib_common.base.state.Empty
import com.bawei.lib_common.base.state.Failed
import com.bawei.lib_common.base.state.Loading
import com.bawei.lib_common.base.state.Success
import com.bawei.lib_common.observeWithLifecycle
import com.bawei.lib_common.utils.TimeUtils
import com.bawei.lib_common.utils.ToastUtils
import com.bawei.lib_storage.AppMMKV
import com.bawei.lib_storage.AuthMMKV
import com.bawei.module_home.R
import com.bawei.module_home.databinding.ActivitySignBinding
import com.bawei.module_home.model.SignParam
import com.bawei.module_home.ui.sign.viewmodel.SignViewModel
import com.bawei.module_home.ui.sign.viewmodel.TimeViewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale

/**
 *author：yjk
 *description:
 *date：2025/6/11
 */
@AndroidEntryPoint
@Route(path = Router.SIGN_PAGE)
class SignActivity : BaseActivity<BaseViewModel, ActivitySignBinding>() {
    override val mLayoutResId: Int
        get() = R.layout.activity_sign

    private val timeViewModel: TimeViewModel by viewModels()
    private val signViewModel: SignViewModel by viewModels()
    override fun initView() {
        super.initView()
        //初始化打卡状态
        initSign()
        //初始化顶部栏
        initTopBar()
        //初始化日期
        mBinding.date.setText(TimeUtils.getCurrentDateFormatted())
        mBinding.punchClockView.refresh()
    }

    override fun initListener() {
        super.initListener()
        //监听动态时间
        lifecycleScope.launch {
            timeViewModel.timeFlow.collect { time ->
                mBinding.time.text = time
            }
        }
        signViewModel.signState.observeWithLifecycle(this){
            when(it){
                Empty -> {}
                is Failed -> {
                    ToastUtils.showLong(this,"打卡失败")
                }
                Loading -> {}
                Success -> {
                    val currentHour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY)
                    if (currentHour < 12) {
                        AuthMMKV.isSignInA = true
                        AuthMMKV.morningSignIn = TimeUtils.getCurrentTime()
                    } else {
                        AuthMMKV.isSignInB = true
                        AuthMMKV.afternoonSignIn = TimeUtils.getCurrentTime()
                    }
                    mBinding.sign.setText("已打卡")
                    mBinding.sign.isClickable = false
                    ToastUtils.showLong(this,"打卡成功")

                }
            }
        }
    }

    fun initTopBar() {
        mBinding.toolbar.title.setText("考勤打卡")
        mBinding.toolbar.back.setOnClickListener {
            finish()
        }
        mBinding.toolbar.more.setOnClickListener{
            ARouter.getInstance().build(Router.SIGNS_PAGE).navigation()
        }
    }

    fun initSign() {
        if (TimeUtils.isMoreThan24Hours(AuthMMKV.morningSignIn)){
            AuthMMKV.isSignInA = false
        }
        if (TimeUtils.isMoreThan24Hours(AuthMMKV.afternoonSignIn)){
            AuthMMKV.isSignInB = false
        }
        //判断打卡状态
        val currentHour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY)
        if (currentHour < 12) {
            if (AuthMMKV.isSignInA) {
                mBinding.sign.setText("已打卡")
            } else {
                mBinding.sign.setText("打卡")
                signInMorning()
            }
        } else {
            if (AuthMMKV.isSignInB) {
                mBinding.sign.setText("已打卡")
            } else {
                mBinding.sign.setText("打卡")
                signInAfternoon()
            }
        }


    }
    fun signInAfternoon(){
        //点击打卡
        mBinding.sign.setOnClickListener {
            val signParam = SignParam(
                TimeUtils.getCurrentDate()+" "+TimeUtils.getCurrentTime(),
                "lat,lon",
                0,
                mBinding.address.text.toString(),
                "",
                checkLeaveStatus(TimeUtils.getCurrentTime()),
                AppMMKV.userId,
                AppMMKV.userId
            )
            signViewModel.signIn(signParam)
        }
    }
    fun signInMorning(){
        //点击打卡
        mBinding.sign.setOnClickListener {
            val signParam = SignParam(
                "",
                "lat,lon",
                0,
                mBinding.address.text.toString(),
                TimeUtils.getCurrentDate()+" "+TimeUtils.getCurrentTime(),
                checkAttendanceStatus(TimeUtils.getCurrentTime()),
                AppMMKV.userId,
                AppMMKV.userId
            )
            signViewModel.signIn(signParam)
        }
    }
    fun checkAttendanceStatus(punchTime: String): Int {
        // 1. 定义时间格式（时:分:秒）
        val timeFormat = SimpleDateFormat("HH:mm:ss", Locale.getDefault())

        // 2. 解析打卡时间和预定时间
        val scheduledTime = timeFormat.parse("09:00:00")!!
        val actualTime = timeFormat.parse(punchTime) ?: return 0 // 解析失败默认正常

        // 3. 计算时间差（分钟）
        val diffMinutes = (actualTime.time - scheduledTime.time) / (1000 * 60)

        // 4. 判断考勤状态
        return when {
            diffMinutes <= 15 && diffMinutes >= -15 -> 0  // 正常（±15分钟内）
            diffMinutes > 15 && diffMinutes <= 60 -> 1     // 迟到（15-60分钟）
            diffMinutes > 60 -> 3                          // 缺勤（超过60分钟）
            else -> 0                                      // 早到（超过15分钟早到也算正常）
        }
    }
    fun checkLeaveStatus(punchTime: String): Int {
        // 1. 定义时间格式（时:分:秒）
        val timeFormat = SimpleDateFormat("HH:mm:ss", Locale.getDefault())

        // 2. 解析打卡时间和下班时间
        val closingTime = timeFormat.parse("18:00:00")!!
        val actualTime = timeFormat.parse(punchTime) ?: return 0 // 解析失败默认正常

        // 3. 比较时间（毫秒数）
        return if (actualTime.before(closingTime)) 1 else 0 // 早退返回1，否则返回0
    }

}